package com.fsoft.core.context;

import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.fsoft.core.common.base.entity.UserVo;
import com.fsoft.core.shiro.ShiroContext;

/**
 * @author licheng
 * @date 2021-04-11
 * @email it.fish2010@foxmail.com
 * @copyright
 */
public class FSContext {
	private static Logger log = LoggerFactory.getLogger(FSContext.class);
	private static final String CONFIG_FILE_DB = "db.properties";
	private static final String CONFIG_FILE_REDIS = "redis.properties";
	private static final Properties properties = new Properties();
	static {
		try {
			InputStream inputStream = FSContext.class.getClassLoader().getResourceAsStream(CONFIG_FILE_DB);
			properties.load(inputStream);
			inputStream.close();
			inputStream = null;

			inputStream = FSContext.class.getClassLoader().getResourceAsStream(CONFIG_FILE_REDIS);
			properties.load(inputStream);
			inputStream.close();
			inputStream = null;
		} catch (Exception e) {
			log.error("加载properties配置文件失败:" + e.getMessage(), e);
		}
	}

	/***
	 * 获取配置项的值
	 * @param key
	 * @return
	 */
	public String getKey(String key) {
		return properties.getProperty(key);
	}

	private static FSContext scontext = null;

	public static FSContext getInstance() {
		synchronized (FSContext.class) {
			if (scontext == null) {
				ApplicationContext cxt = getApplicationContext();
				FSContext zlcxt = (FSContext) cxt.getBean("FSContext");
				scontext = zlcxt;
			}
		}
		return scontext;
	}

	@SuppressWarnings("unchecked")
	public <T> T getBean(String name) {
		return (T) FSContext.getApplicationContext().getBean(name);
	}

	/**
	 * 添加按照class对象获取注入对象
	 * @author licheng
	 * @date 2021-04-11
	 * @param className
	 * @return
	 */
	public <T> T getBean(Class<T> className) {
		return (T) FSContext.getApplicationContext().getBean(className);
	}

	/**
	 * 获取spring 的ApplicationContext 注意：这里不是springMVC的 ApplicationContext 如果需要 请使用getMVCApplicationContext.
	 * @author licheng
	 * @date 2021-04-11
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return SpringContextUtil.getSpringApplicationContext();
	}

	/**
	 * 获取spring MVC的ApplicationContext 它的父ApplicationContext是spring的ApplicationContext <br>
	 * 注意：这里不是spring的 ApplicationContext 如果需要 请使用getApplicationContext.
	 * @author licheng
	 * @date 2021-04-11
	 * @return
	 */
	public static ApplicationContext getMVCApplicationContext() {
		return SpringContextUtil.getSpringMvcApplicationMvcContext();
	}

	/***
	 * 获取当前登录用户信息
	 * @author licheng
	 * @date 2021-04-12
	 * @return
	 */
	public UserVo getUser() {
		return ShiroContext.getCurrentUser();
	}

}
